package org.origin.ferret.authority.center.security;

import org.origin.centre.model.consts.XConst;
import org.origin.centre.security.authentication.details.XUserDetailsService;
import org.origin.centre.security.user.XUser;
import org.origin.centre.support.lang.XList;
import org.origin.centre.support.lang.XMap;
import org.origin.centre.support.mapper.CamelCaseColumnMapRowMapper;
import org.origin.centre.support.utils.MapUtil;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.ColumnMapRowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.util.List;
import java.util.Map;

/**
 * spring security user account service 配置
 *
 * @author ferret
 * @version 2024-05-08
 */
@Service
public class DefaultUserAccountService implements XUserDetailsService {
    protected final String selectSql;
    protected final NamedParameterJdbcTemplate jdbcTemplate;
    protected ColumnMapRowMapper rowMapper = new CamelCaseColumnMapRowMapper();

    public DefaultUserAccountService(DataSource dataSource) {
        this.jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
        this.selectSql = "SELECT id,account,password,status FROM sys_user WHERE account = :account";
    }

    @Override
    public List<String> getClientIds() {
        return new XList<String>()
                .of(XConst.DEFAULT_CLIENT);
    }

    @Override
    public UserDetails getByAccount(String clientId, String account) {
        try {
            ColumnMapRowMapper rowMapper = this.rowMapper;
            NamedParameterJdbcTemplate jdbcTemplate = this.jdbcTemplate;
            XMap<String, Object> params = new XMap<String, Object>()
                    .of(XConst.ACCOUNT, account);
            Map<String, Object> userDetails = jdbcTemplate.queryForObject(selectSql, params, rowMapper);
            return new XUser()
                    .setId(MapUtil.getString(userDetails, XConst.ID))
                    .setAccount(MapUtil.getString(userDetails, XConst.ACCOUNT))
                    .setPassword(MapUtil.getString(userDetails, XConst.PASSWORD))
                    .setStatus(MapUtil.getInteger(userDetails, XConst.STATUS))
                    .setAdmin(XConst.ADMIN_ID.equals(MapUtil.getString(userDetails, XConst.ID)))
                    .setClientId(clientId);
        } catch (EmptyResultDataAccessException e) {
            throw new IllegalArgumentException("未查询到用户！");
        }
    }

}
